<template>
  <div>
    <ContentTable>
      <template #menu>
        <div class="menus">
          <div class="menus-item">
            <div class="menus-items">
              <el-select v-model="inf.value" @change="getChange" placeholder="请选择" style="width: 140px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input v-model="inf.key" :disabled="inf.active" placeholder="输入关键字" clearable :suffix-icon="Search" />
            </div>

            <el-button type="primary" @click="getData">搜索</el-button>
            <el-button type="success" :disabled="inf.export" @click="getExport">导出</el-button>
          </div>
        </div>
      </template>
      <div class="table" v-if="tableData.length > 0">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4" class="tableTile">
                <div>
                  <h3>成长</h3>
                  <p m="t-0 b-2">段位: {{ props.row.state }}</p>
                  <p m="t-0 b-2">等级: {{ props.row.city }}</p>
                  <p m="t-0 b-2">每个模式场次: {{ props.row.address }}</p>
                </div>
                <div>
                  <h3>成长2</h3>
                  <p m="t-0 b-2">超新星等级: {{ props.row.state }}</p>
                  <p m="t-0 b-2">成就点数: {{ props.row.city }}</p>
                  <p m="t-0 b-2">排行榜排名: {{ props.row.address }}</p>
                </div>
                <div>
                  <h3>商业化</h3>
                  <p m="t-0 b-2">英雄数量: {{ props.row.state }}</p>
                  <p m="t-0 b-2">皮肤数量: {{ props.row.city }}</p>
                  <p m="t-0 b-2">棋盘数量: {{ props.row.address }}</p>
                  <p m="t-0 b-2">VIP等级: {{ props.row.zip }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="UID" prop="date" />
          <el-table-column label="AIID" prop="name" />
          <el-table-column label="能力" prop="state" />
          <el-table-column label="活跃时间" prop="city" />
          <el-table-column label="标签" prop="zip" />
        </el-table>
      </div>
    </ContentTable>
    <!-- <div class="pagination">
      <el-pagination size="small" background layout="total, prev, pager, next, jumper, sizes" v-model:current-page="inf.page" v-model:page-size="inf.size" :total="inf_res.total" @current-change="getData" @size-change="getData" />
    </div> -->
  </div>
</template>
<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import { ref, computed, getCurrentInstance, onMounted } from 'vue'
import { OSProto } from '@/proto/os_msg'
// import http from '@/api/core/http.ts'
import { postTest } from '@/api'
const instance = getCurrentInstance()
const $xlsx = instance?.appContext.config.globalProperties.$xlsx
const inf = ref({
  value: '',
  key: '',
  page: 1,
  size: 10,
  active: true,
  export: true,
})
const options = [
  {
    value: 'name',
    label: '名字',
  },
  {
    value: 'showid',
    label: 'showid',
  },
  {
    value: 'UID',
    label: 'UID',
  },
]
const inf_res: any = ref({
  total: 0,
})
// 没有选择不能输入
const getChange = (value: string) => {
  if (value) {
    inf.value.active = false
  } else {
    inf.value.active = true
  }
}
interface FamilyMember {
  name: string
  state: string
  city: string
  address: string
  zip: string
}

interface Person {
  date: string
  name: string
  state: string
  city: string
  address: string
  zip: string
  family: FamilyMember[]
}
const tableData = ref<Person[]>([])
const tableData1 = ref([
  {
    date: 'UID',
    name: 'AIID',
    state: 'California',
    city: '2025-3-3',
    address: '3650 21st St, San Francisco',
    zip: 'CA 94114',
    family: [
      {
        name: 'Jerry',
        state: 'California',
        city: 'San Francisco',
        address: '3650 21st St, San Francisco',
        zip: 'CA 94114',
      },
      {
        name: 'Spike',
        state: 'California',
        city: 'San Francisco',
        address: '3650 21st St, San Francisco',
        zip: 'CA 94114',
      },
      {
        name: 'Tyke',
        state: 'California',
        city: 'San Francisco',
        address: '3650 21st St, San Francisco',
        zip: 'CA 94114',
      },
    ],
  },
])
// 查询
const getData = () => {
  let _inf = JSON.parse(JSON.stringify(inf.value))
  if (!_inf.key) return (inf.value.export = true)
  inf.value.export = false
  tableData.value = tableData1.value

  const message = new OSProto.CSTestMsg.req()
  message.UID = 1
  const binaryData = JSON.stringify(message)
  const obj = {
    msgid: 'CSTestMsg.req',
    uid: 12,
  }
  postTest(obj,{}).then((buffer) => {
    console.log('收到的消息：', buffer)
  })
  // http.post('/genericjson?msgid=CSTestMsg.req&uid=1', {
  //   method: 'POST',
  //   headers: { 'Content-Type': 'application/octet-stream' },
  //   body: binaryData,
  // })
  //   .then((buffer) => {
  //     const res = new OSProto.CSTestMsg.res()
  //     const message: OSProto.CSTestMsg.res = JSON.parse('{ "uid": 1 }')
  //     console.log('收到的消息：', buffer)
  //   })
  //   .catch((error) => console.error('请求失败:', error))
}

const s2ab = (s: string) => {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xff
  }
  return buf
}
// 生成表头
const generateHeaders = (data: any[]) => {
  const headers = new Set() // 用 Set 来去重

  // 遍历 data
  data.forEach((item) => {
    // 提取每一项的字段（主数据部分）
    Object.keys(item).forEach((key) => {
      if (key !== 'family') {
        // 排除 family 部分，稍后单独处理
        headers.add(key)
      }
    })

    // 提取 family 的字段
    if (item.family && item.family.length > 0) {
      Object.keys(item.family[0]).forEach((familyKey) => {
        headers.add(`Family ${familyKey}`)
      })
    }
  })

  return [...headers] // 返回一个数组形式的表头
}
// 导出按钮
const getExport = () => {
  const headers = generateHeaders(tableData.value) // 动态生成表头
  // 转换数据
  const transformedData: any[][] = []
  tableData.value.forEach((item: { [x: string]: any; family: any[] }) => {
    item.family.forEach((familyMember) => {
      const row: any[] = []
      // 填充主数据部分
      headers.forEach((header: any) => {
        if (header.startsWith('Family')) {
          // 提取 family 数据
          const familyField = header.split(' ')[1] // 获取 'Family name', 'Family state' 等
          row.push(familyMember[familyField])
        } else {
          // 填充主数据部分（例如 date, name, state 等）
          row.push(item[header] || '') // 如果字段没有值，填充为空
        }
      })
      transformedData.push(row)
    })
  })

  // 将表头与数据合并
  const result = [headers, ...transformedData]
  const ws = $xlsx.utils.aoa_to_sheet(result)
  const wb = $xlsx.utils.book_new()
  $xlsx.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 3. 将工作簿转化为二进制字符串（注意：类型应该是 binary）
  const excelData = $xlsx.write(wb, { bookType: 'xlsx', type: 'binary' })

  // 4. 转换二进制字符串为 ArrayBuffer
  const blobData = new Blob([s2ab(excelData)], { type: 'application/octet-stream' })

  // 5. 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blobData)
  link.download = 'example.xlsx' // 文件名
  link.click()
}
</script>
<style scoped lang="scss">
.menus {
  padding: 20px;
  display: flex;
  align-items: center;
  .menus-item {
    display: flex;
    align-items: center;
    gap: 10px;
    .menus-items {
      display: flex;
    }
  }
}
.table {
  padding: 5px;
  .tableTile {
    padding: 10px;
    display: flex;
    justify-content: space-around;
  }
}
.pagination {
  padding: 0 20px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
